// pages/common/authorization/authorization.js
const app = getApp()
const WXAPI = require('../../api/api');
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    authorizaData:{
      type: Object,
      value: {},
    }   
    
  },

  /**
   * 组件的初始数据
   */
  data: {
    code: '',
    appid: app.globalData.appid,
    phone: '',
    encryption: '',
    isUesrBox: false,
  },
  attached(){
    this.getCode()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getCode(){
      // 登录 
      let that = this;
      wx.login({
        success: function(res) {
          if (res.code) {
            that.setData({
              code: res.code
            })
            console.log('获取code',that.data.code)
          } else {
            console.log('获取code失败' ,res.errMsg)
          }
        }
      })
    },
    //授权用户信息
    getUserProfile(e){
      let that = this;
      let phone = this.properties.authorizaData.phone;
      let sessionKey = this.properties.authorizaData.sessionKey;
      let encryption = this.properties.authorizaData.encryption
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log("res", res)
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          var data ={
            appid: that.data.appid,
            sessionKey: sessionKey,
            encryptedData: res.encryptedData,
            iv: res.iv,
            signature: res.signature,
            rawData: res.rawData,
            phone: phone,
            encryption: encryption,
            source: app.globalData.source,//用户来源
          }
          WXAPI.newuserLogin( data ,(res) =>{
            console.log("用户登录成功",res)
            let data = res.result
            wx.setStorageSync('token',data.token)
            that.setData({
              isUesrBox: false,
            })
            that.triggerEvent("parentComponentFunction");
          })
        },
        fail(res) {
          console.log("获取用户信息失败", res)
        }
      })
     
    },
    //用户信息授权弹框
    showUser(){
      this.setData({
        isUesrBox: true
      })
    },
    hideUser(){
      this.setData({
        isUesrBox: false
      })
    },
    //不同意用户信息授权
    handlecancel(){
      this.setData({
        isUesrBox: false,
      })
    },
    getclose(){
      console.log(1111111)
      let that = this
      that.triggerEvent("notokenFuntion");
      this.setData({
        isUesrBox: false,
      })
    }
  }
})
